package net.jueb.frameworkDemo.mq.activeMq.pubSub;

import java.util.Scanner;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SubClient implements MessageListener {

	private static final Logger LOGGER = LoggerFactory.getLogger(SubClient.class);
//	private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	MessageConsumer consumer;

	public SubClient(Session session,String topic) throws JMSException {
		// 通过会话创建目标
		Destination dest = session.createTopic(topic);
		// 创建mq消息的消费者
		consumer = session.createConsumer(dest);
		consumer.setMessageListener(this);
	}
	
	public static void main(String[] args) throws JMSException {
		String BROKER_URL = "failover:(tcp://192.168.0.205:61616)?maxReconnectAttempts=-1&maxReconnectDelay=10000&timeout=-1";
		String TOPIC = "test-activemq-topic";
		// 初始化ConnectionFactory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);

		// 创建mq连接
//		Connection conn = connectionFactory.createConnection();
		Connection conn = connectionFactory.createConnection("admin", "admin");
		// 启动连接
		conn.setExceptionListener(new ExceptionListener() {
			@Override
			public void onException(JMSException exception) {
				System.out.println(exception.getMessage());
			}
		});
		conn.start();
		// 创建会话
		Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		SubClient me1 = new SubClient(session,TOPIC);
		SubClient me2 = new SubClient(session,TOPIC);
		new Scanner(System.in).nextLine();
	}

	@Override
	public void onMessage(Message message) {
		TextMessage txtMessage = (TextMessage) message;
		try {
			LOGGER.info("get message " + txtMessage.getText());
		} catch (JMSException e) {
			LOGGER.error("error {}", e);
		}
	}
}
